package test;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;

/**
 * @author Tang
 * @classname ThreadDemo01
 * @description [  ]
 * @date 2021/2/24 20:45
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
class Res {
    public String name;
    public Integer age;
    public boolean isRead;
    public int count;
}

class InThread extends Thread {

    Res res;

    public InThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                // 没有读
                if (res.isRead) {
                    try {
                        // 等待读
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 可以写
                if (!res.isRead) {
                    res.count++;
                    if (res.count % 2 == 0) {
                        res.name = "小龙";
                        res.age = 100;
                    } else {
                        res.name = "小红";
                        res.age = 99;
                    }
                    res.isRead = true;
                    res.notify();
                }
            }
        }
    }
}

class OutThread extends Thread {

    Res res;

    public OutThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                // 等待写
                if (!res.isRead) {
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 可以读
                if (res.isRead) {
                    System.out.println(res.name + "---" + res.age + "---" + res.count);
                    // 已读
                    res.isRead = false;
                    res.notify();
                }
            }
        }
    }
}

public class ThreadDemo01 {

    public static void main(String[] args) {
        Res res = new Res("tang", 0, true, 1);
        new InThread(res).start();
        new OutThread(res).start();
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}